package player

import (
	"fmt"
	"math/rand"
	"strings"
	"tcs-server/tcs-design/src/modules/tables"
	pctx "tcs-server/tcs-game-server/src/foundation/player"
	player "tcs-server/tcs-game-server/src/module/player/model"
	players "tcs-server/tcs-game-server/src/module/player/service"
	"tcs-server/tcs-protobuf/src/tcsprotobuf"

	"go.uber.org/zap"
)

var HANDLER *PlayerHandler

func init() {
	fmt.Println("PlayerHandler")
}

type PlayerHandler struct {
	Proto_Login     func() `PlayerCmd:"method=Login,needLogin=false,enum=tcs.PlayerLoginRequest.Proto,enumName=ID"`
	Proto_HeartBeat func() `PlayerCmd:"method=HeartBeat,needLogin=true,enum=tcs.HeartBeatRequest.Proto,enumName=ID"`
	// proto_Create func() `proto:"method=Create,needLogin=false,enum=pb.CreateRoleRequest.Proto,enumName=ID"`
}

func (h *PlayerHandler) Login(playerContext *pctx.PlayerContext, request *tcsprotobuf.PlayerLoginRequest) *tcsprotobuf.PlayerLoginResponse {
	fmt.Println("request.OpenId", request.OpenId)
	fmt.Println("Login", tcsprotobuf.PlayerLoginRequest_ID.Number())

	openId := strings.TrimSpace(request.OpenId)
	// userId := strings.TrimSpace(request.u)

	zap.L().Info(fmt.Sprintf("tables.GlobalTable.AAA %v", tables.GlobalTable.AAA))

	entity := players.Service().GetIdByUserIdAndServerId(openId, request.ServerId)
	if entity == nil {
		defer func() {
			if err := recover(); err != nil {
				entity = players.Service().GetIdByUserIdAndServerId(openId, request.ServerId)
			}
		}()
		entity = &player.Player{}
		entity.UserId = openId
		entity.OpenId = openId
		entity.ServerId = request.ServerId
		entity.Nick = fmt.Sprintf("%s_%v", "nick", rand.Int63n(987654321))
		entity.Level = 1
		players.Service().Insert(entity)
	}

	var response tcsprotobuf.PlayerLoginResponse
	response.ServerTime = 123
	response.LoginStatus = tcsprotobuf.PbLoginStatus_NORMAL
	response.Player = buildPbPlayer(entity)
	return &response
}

func buildPbPlayer(player *player.Player) *tcsprotobuf.PbPlayer {
	var builder tcsprotobuf.PbPlayer
	builder.Id = player.Id
	builder.Nick = player.Nick
	return &builder
}

func (h *PlayerHandler) HeartBeat(playerContext *pctx.PlayerContext, request *tcsprotobuf.HeartBeatRequest) *tcsprotobuf.HeartBeatResponse {
	var response tcsprotobuf.HeartBeatResponse
	response.ServerTime = 123
	return &response
}
